let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    remark: '',
    goods_list: [],
    order_total_price: 0,
    order_total_num: 0,
    exist_address: false, // 是否存在收货地址
    address: null, // 默认收货地址
    paytype: "1"
  },
  onSubmit() {
    var that = this;
    if (!that.data.exist_address) {
      wx.showToast({
        title: '请先添加收货地址',
        icon: 'error'
      })
      return
    }


    wx.showLoading({
      title: '正在创建订单...'
    });
 
    var obj = {};
    obj.total_price = this.data.order_total_price;
    obj.goodlist = JSON.stringify(this.data.goods_list);
    obj.address_id = this.data.address.id,
      obj.paytype = this.data.paytype;

    App._post_form('wxapi/order/add', obj, result => {


      if (that.data.paytype == "1") {
        App._post_form('wxapi/pay', {
          order_id: result.order_id
        }, res => {
          wx.hideLoading()
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: 'MD5',
            paySign: res.data.paySign,
            success(success) {
              console.log('支付成功', success)

              wx.redirectTo({
                url: '/pages/order/orderDetails/orderDetails?order_id=' + result.order_id,
              });

            },
            fail(err) {
              console.log('取消支付')
              wx.showToast({
                title: '支付失败',
                icon: 'error',
                success: function () {


                }
              })

            }
          })
        });
      } else {

        wx.redirectTo({
          url: '/pages/order/orderDetails/orderDetails?order_id=' + result.order_id,
        });


      }


    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("options", options);
    this.setData({
      order_total_num: options.num,
      goods_list: [options],
      order_total_price: options.num * options.goods_price
    })


    console.log("goods_list", this.data.goods_list);
    if (options.order_type == 'cart') {
      this.getCartList()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddressList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  getAddressList() {
    App._post_form('wxapi/address/lists', {}, res => {
      if (res.status == 200) {
        // 有收货地址
        if (res.data.length !== 0) {
          this.data.exist_address = true;
          res.data.forEach(item => {
            if (item.id == res.default_id) {
              this.setData({
                address: Object.assign({}, item)
              })
            }
          })
        }
      }
    })
  },
  getCartList() {
    App._post_form('wxapi/cart/lists', {
      token: wx.getStorageSync('token')
    }, res => {
      if (res.status == 200) {
        // 购物车列表
        res.data.list.forEach(item => {
          item.total_num = item.num
        })
        this.setData({
          goods_list: res.data.list,
          order_total_price: parseFloat(res.data.order_total_price).toFixed(2)
        })
        // 计算总数
        if (res.data.list.length > 1) {
          this.setData({
            order_total_num: res.data.list.reduce((a, b) => {
              return a + b.num
            }, 0)
          })
        } else {
          this.setData({
            order_total_num: res.data.list[0].num
          })
        }
      }
    })
  },
  onChange(event) {
    this.setData({
      paytype: event.detail,
    });
  },
})